<template>
  <div class="todo-page">
    <!-- 顶部导航 -->
    <header class="header">
      <h1>待办事项 Demo</h1>
      <a class="repo-link" href="https://gitee.com/admin-heyi/group-9--vue-project-1" target="_blank">
        🔗 仓库地址
      </a>
    </header>

    <main class="content">
      <!-- 左侧：组件目录结构 -->
      <aside class="sidebar">
        <h2>📂 组件目录结构</h2>
        <ul>
        <li v-for="c in components" :key="c.name">
        <h3>{{ c.name }} <small>({{ c.path }})</small></h3>
        <p><strong>Props:</strong> {{ c.props.length ? c.props.join(", ") : "无" }}</p>
        <p><strong>Emits:</strong> {{ c.emits.length ? c.emits.join(", ") : "无" }}</p>
        <p><strong>Methods:</strong> {{ c.methods.length ? c.methods.join(", ") : "无" }}</p>
        <hr />
      </li>
        </ul>
      </aside>

      <!-- 右侧：待办事项功能 -->
      <section class="todo-section">
        <TodoFilter v-model="filter" :user="user" @logout="logout" />
        <TodoInput @add="addTask" />
        <TodoList
          :tasks="filteredTasks"
          @toggle="toggleTask"
          @remove="removeTask"
          @update="updateTask"
        />
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import TodoInput from '@/components/TodoInput.vue'
import TodoList from '@/components/TodoList.vue'
import TodoFilter from '@/components/TodoFilter.vue'
import { getCurrent, clearCurrent, getTasks, setTasks } from '@/utils/storage'
import components from '@/componentsInfo'

const router = useRouter()
const user = ref('')
const tasks = ref<any[]>([])
const filter = ref('全部')

onMounted(() => {
  const current = getCurrent()
  if (!current) router.push('/login')
  else {
    user.value = current
    tasks.value = getTasks(user.value)
  }
})

const filteredTasks = computed(() => {
  switch (filter.value) {
    case '已完成': return tasks.value.filter(t => t.completed)
    case '未完成': return tasks.value.filter(t => !t.completed)
    default: return tasks.value
  }
})

watch(tasks, (newTasks) => {
  setTasks(user.value, newTasks)
}, { deep: true })

const addTask = (title: string) =>
  tasks.value.push({ id: Date.now(), title, completed: false, editing: false })

const toggleTask = (id: number) => {
  const t = tasks.value.find(t => t.id === id)
  if (t) t.completed = !t.completed
}

const removeTask = (id: number) =>
  tasks.value = tasks.value.filter(t => t.id !== id)

const updateTask = (updatedTask: any) => {
  const index = tasks.value.findIndex(t => t.id === updatedTask.id)
  if (index !== -1) tasks.value[index] = { ...updatedTask }
}

const logout = () => { clearCurrent(); router.push('/login') }
</script>

<style scoped src="@/assets/TodoPage.css"></style>
